<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :show-message="false" label-width="110px">
      <el-form-item label="应用图标" prop="applicationLogo" required>
        <ImageUpload
          v-model="form.applicationLogo"
          :disabled="userInfo.userType !== 0"
        />
      </el-form-item>
      <el-form-item label="应用编码" prop="applicationKey" required>
        <span
          v-if="
            userInfo.userType !== 0 ||
            (!!form.applicationId && !!form.applicationKey)
          "
          >{{ form.applicationKey }}</span
        >
        <el-input
          v-else
          v-model="form.applicationKey"
          placeholder="请输入应用唯一编码"
          :maxLength="12"
        />
      </el-form-item>
      <el-form-item label="应用名称" prop="applicationName" required>
        <span v-if="userInfo.userType !== 0">{{ form.applicationName }}</span>
        <el-input
          v-else
          v-model="form.applicationName"
          placeholder="请输入应用名称"
          :maxLength="20"
        />
      </el-form-item>
      <el-form-item label="应用简介" prop="applicationDesc">
        <span v-if="userInfo.userType !== 0">{{ form.applicationDesc }}</span>
        <el-input
          v-else
          v-model="form.applicationDesc"
          type="textarea"
          :rows="2"
          placeholder="请输入备注"
        />
      </el-form-item>
      <el-form-item label="状态" prop="applicationStatus">
        <el-switch
          v-model="form.applicationStatus"
          :active-value="1"
          active-text="启用"
          :inactive-value="0"
          inactive-text="禁用"
          :disabled="userInfo.userType !== 0"
          @change="changeStatus(form)"
        >
        </el-switch>
      </el-form-item>
      <el-form-item
        v-if="userInfo.userType === 0 || userInfo.userType === 3"
        label="渠道可见范围"
      >
        <div>
          <el-cascader
            ref="Cascader"
            v-model="checkedChannel"
            class="width100"
            placeholder="选择可见渠道"
            :options="channelTree"
            :props="{
              multiple: true,
              value: 'id',
              emitPath: false,
              checkStrictly: true,
            }"
            collapse-tags
            clearable
            filterable
          >
            <template slot-scope="{ node, data }">
              <span>{{ data.label }}</span>
              <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
            </template>
          </el-cascader>
        </div>
      </el-form-item>
      <el-form-item v-if="userInfo.userType !== 0" label="直属单位开通">
        <el-radio-group v-model="form.authScope">
          <el-radio :label="0">全部直属单位可见</el-radio>
          <el-radio :label="1">部分直属单位可见</el-radio>
        </el-radio-group>
        <div>
          <el-select
            v-if="form.authScope === 1"
            v-model="form.companyAuthList"
            value-key="deptId"
            placeholder="请选择单位"
            multiple
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in companyTree"
              :key="item.deptId"
              :label="item.label"
              :value="item"
            >
            </el-option>
          </el-select>
        </div>
      </el-form-item>
    </el-form>

    <FixedBottomButton>
      <el-button
        v-if="form.applicationId"
        type="primary"
        size="medium"
        @click="seve"
        >保存修改</el-button
      >
      <el-button v-else type="primary" size="medium" @click="seve"
        >确认新增</el-button
      >
    </FixedBottomButton>
  </div>
</template>

<script>
import ImageUpload from "@/components/ImageUpload";
import { appTreeselect, companyChildrenList } from '@/api/system/dept.js'
import { addApply, updateApply, getApplyDetail } from '@/api/system/apply.js'
import { deepClone } from '@/utils';
import FixedBottomButton from '@/components/FixedBottomButton'

export default {
  name: "ApplyDetail",
  components: {
    ImageUpload,
    FixedBottomButton
  },
  computed: {
    userInfo() {
      return this.$store.state.user.userInfo;
    },
  },
  created() {
    // deptId: 部门ID  saasType: 部门类型 0:平台，1:渠道，2:单位，3:部门(原科室), 4层级部门

    this.getData()
    this.getTreeList();
  },
  data() {
    return {
      form: {
        applicationId: undefined,
        applicationKey: undefined, // 应用唯一编码
        applicationLogo: undefined,
        applicationName: undefined,
        applicationDesc: undefined,
        applicationStatus: 1, // 状态: 0停用 1启用
        applicationType: 0, // 应用类型: 0平台
        authScope: 0, // 直属下级单位权限范围: 0全部单位可见 1部分单位可见
        companyAuthList: [], // 直属单位列表
        // authList 渠道列表
        // cancelAuthList 停用渠道列表 需对比就数据得出
      },

      channelTree: [],
      checkedChannel: [],

      companyTree: []
    }
  },
  methods: {
    getData() {
      const { applicationId } = this.$route.query;
      if (!applicationId) return;
      getApplyDetail({ applicationId }).then(res => {
        this.form = res.data;
        this.checkedChannel = res.data.authList.map(v => v.deptId);
      })
    },
    getTreeList() {
      // 只获取渠道
      appTreeselect({ neSaasTypes: '2,3,4' }).then(res => {
        this.channelTree = res.data;
      })
      companyChildrenList().then(res => {
        this.companyTree = res.data.map(item => {
          return {
            deptId: item.deptId,
            saasType: item.saasType,
            label: item.deptName,
          }
        });
      })
    },
    // 修改状态
    changeStatus(row) {
      const that = this;
      if (row.applicationStatus !== 1) {
        that.$confirm('应用禁用后，平台所有机构均无法使用该应用，请谨慎操作。是否确定要禁用该应用？', '提示', {
          distinguishCancelAndClose: true,
          type: 'warning',
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => { }).catch(() => {
          row.applicationStatus = row.applicationStatus ? 0 : 1; // 修改失败,复位
        });
      }
    },
    seve() {
      const that = this;

      console.log(JSON.parse(JSON.stringify(that.form)));

      that.$refs["form"].validate(async (valid) => {
        if (valid) {
          const params = deepClone(that.form);

          if (that.userInfo.userType === 0 || that.userInfo.userType === 3) {
            const checkedList = that.$refs.Cascader.getCheckedNodes();
            params.authList = checkedList.map(node => {
              return {
                deptId: node.data.id,
                saasType: node.data.depitType,
              }
            })

            const newCheckedIds = params.authList.map(v => v.deptId);
            params.cancelAuthList = that.form.authList.filter(item => !newCheckedIds.includes(item.deptId));
          }

          if (params.authScope === 0) { // 全部单位可见不传已选单位
            params.companyAuthList = undefined;
          }

          if (params.applicationId) {
            await updateApply(params)
          } else {
            await addApply(params);
          }
          that.$message.success(params.applicationId ? "修改成功" : "新增成功");
          that.$router.go(-1);
        }
      })
    }
  },

}
</script>

<style lang="scss" scoped>
</style>
